package com.yjps.house.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yjps.common.message.Message;
import com.yjps.common.page.Pager;
import com.yjps.house.model.Shop;
import com.yjps.house.model.ShopApplyHistory;
import com.yjps.house.service.ShopService;
import com.yjps.system.model.User;
import com.yjps.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 门店控制类
 *     |--后台接口
 *           |--/system/apply/list  系统管理员获取门店申请列表
 *           |--/system/apply/verify  系统管理员审核门店申请
 *           |--/system/apply/getApply  根据指定id获取门店申请记录
 *           |--/system/apply/getShop   系统后台获取指定id的门店实例shop的json对象
 *    |--前台接口
 *           |--/house/shop/apply/update  更新申请
 *           |--/house/shop/apply  用户申请门店
 */
@Controller
public class ShopController {

    @Autowired
    ShopService shopService;
    @Autowired
    UserService userService;

    /**
     * 用户申请门店
     * @param json {apply:{userId:"",reason:""},shop:{"userId":"","Name":"","logo":"","description":""}}
     * @return {shopId:""}
     */
    @RequestMapping(value = "/house/shop/apply.do",method = RequestMethod.POST )
    @ResponseBody
    public String apply(@RequestParam(value = "json") String json,HttpServletResponse response){
        //解析json
        JSONObject object = JSON.parseObject(json);
        JSONObject apply = JSON.parseObject(object.getString("apply"));
        int userId = Integer.parseInt(apply.getString("userId"));
        String reason=apply.getString("reason");

        Shop shop = JSON.parseObject(object.getString("shop"), Shop.class);

        int shopId=shopService.applyShop(userId,reason,shop);

        //返回
        Message message;
        if (shopId>0){
            Map<String,Object> map=new HashMap<>();
            map.put("shopId",shopId);
            message=new Message(true,"门店申请操作成功",map);
        }else {
            message=new Message(false,"门店申请操作失败");
        }
//        response.setHeader("Access-Control-Allow-Origin","*");
        return message.toJson();
    }

    /**
     * 系统管理员获取门店申请列表
     * @param acceptResult 申请记录操作结果 作为 查询参数
     * @param
     * @return
     */
    @RequestMapping(value = "/system/apply/list",method = RequestMethod.GET)
    public String list(String acceptResult,HttpServletRequest request,HttpServletResponse response,Model model) throws Exception {
        Pager<ShopApplyHistory> pager = shopService.getApplyByPager(new Pager<ShopApplyHistory>(request, response), acceptResult);
        if(pager.getCount()>0)
        for (ShopApplyHistory shopApplyHistory:pager.getList()){
            User user = userService.findUser(shopApplyHistory.getApplyUserId());
            shopApplyHistory.setApplyUser(user.getRealName());
            Shop shop = shopService.findShop(shopApplyHistory.getShopId());
            shopApplyHistory.setApplyShopName(shop.getName());
            User handler = userService.findUser(shopApplyHistory.getHandleUserId());
            shopApplyHistory.setHandlerUser(handler.getRealName());
        }
        model.addAttribute(pager);
        return "system/apply/list";
    }

    /**
     * 系统管理员审核门店申请
     * @param id 门店申请记录id
     * @param shopId 被申请门店id
     * @param applyUserId  申请用户id
     * @param handle 审核操作 1--通过 2--拒绝
     * @return
     */
    @RequestMapping(value = "/system/apply/verify",method = RequestMethod.GET)
    public String verify(@RequestParam(value = "id",required = true) String id,
                         @RequestParam(value = "shopId",required = true) String shopId,
                         @RequestParam(value = "applyUserId",required = true) String applyUserId,
                         @RequestParam(value = "handle",required = true)String handle,HttpServletRequest request){
            User user = (User) request.getSession().getAttribute("loginUser");
            shopService.verifyShop(Integer.parseInt(applyUserId), Integer.parseInt(shopId),
                    Integer.parseInt(handle), Integer.parseInt(id), user.getId());
        return "redirect:/system/apply/list";
    }

    /**
     * 根据指定id获取门店申请记录
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/system/apply/getApply",method = RequestMethod.GET)
    public String getApply(@RequestParam(value = "id",required = true)String id){
        ShopApplyHistory shopApplyHistory = shopService.findApply(Integer.parseInt(id));
        shopApplyHistory.setHandlerUser(userService.findUser(shopApplyHistory.getHandleUserId()).getRealName());
        System.out.println("s = " + shopApplyHistory);
        return shopApplyHistory.toJson();
    }

    /**
     * 门店经理更新门店信息
     * @param json {shop:{"":""...}}
     * @return
     */
    @RequestMapping(value = "/house/shop/apply/update.do",method = RequestMethod.POST )
    @ResponseBody
    public String updateShop(@RequestParam(value = "json") String json,HttpServletResponse response){
        JSONObject object = JSON.parseObject(json);
        Shop shop = JSON.parseObject(object.getString("shop"), Shop.class);
        boolean flag = shopService.updateShop(shop);
        Message message;
        if (flag) {
            message = new Message(true, "update successfully");
        } else {
            message = new Message(flag, "update failed");
        }
//        response.setHeader("Access-Control-Allow-Origin", "*");
        return message.toJson();
    }

    /**
     * 系统后台获取指定id的门店实例shop的json对象
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/system/apply/getShop",method = RequestMethod.GET)
    public String getShop(@RequestParam(value = "id",required = true)String id){
        Shop shop = shopService.findShop(Integer.parseInt(id));
        System.out.println("json = " + shop.toJson());
        return shop.toJson();
    }

    /**
     * 根据经纪人用户id获取门店
     * @param userId
     * @param response
     * @return
     */
    @RequestMapping(value = "/house/shop/get.do", method = RequestMethod.POST)
    @ResponseBody
    public String getShop(@RequestParam(value = "userId") String userId, HttpServletResponse response) {

        Shop shop = shopService.getShopByUserId(Integer.parseInt(userId));
        Message message;
        if (shop != null) {
            message = new Message(true, "get a shop successfully", shop);
        } else {
            message = new Message(false, "get failed");
        }
//        response.setHeader("Access-Control-Allow-Origin", "*");
        return message.toJson();
    }
}
